package com.alianzamedica.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.objectsearch.sqlsearch.ObjectSearch;
import org.w3c.dom.Document;

import com.alianzamedica.businessobject.Drug;
import com.alianzamedica.businessobject.Prescription;
import com.alianzamedica.businessobject.PrescriptionDetail;
import com.alianzamedica.connection.ConnectionImpl;
import com.alianzamedica.models.PrescriptionSellingModel;
import com.alianzamedica.models.TagModel;
import com.alianzamedica.tools.Enviroment;

/**
 * @author Carlos
 * 
 */
public class PrescriptionInfo extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6521369658818266405L;

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		try {
			String attachment = request.getParameter("attachment");
			// String imei = request.getParameter("imeiID");
			if (attachment.equalsIgnoreCase("download")) {
				getPrescriptionDetails(request, out);
			} else if (attachment.equalsIgnoreCase("config")) {
				String imei = request.getParameter("imeiID");
				String resp = this.showConfig(imei);
				out.print(resp);
			} else {
				try {
					getUpdater(request, out);
					String ack = this.showAck("123");
					out.print(ack);
				} catch (Exception ex) {
					ex.printStackTrace();
					String nack = this.showNack("123");
					out.print(nack);
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (Exception e2) {
			}
		}
	}

	private String showNack(String msgID) {
		StringBuffer buffer = new StringBuffer();
		String nl = "\r\n";

		buffer.append("<html>").append(nl);
		buffer.append("<body>").append(nl);
		buffer.append("MSGID = " + msgID + ";</br>").append(nl);
		buffer.append("UPDATE = NAK;</br>").append(nl);
		buffer.append("</body>").append(nl);
		buffer.append("</html>").append(nl);
		return buffer.toString();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.processRequest(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.processRequest(req, resp);
	}

	@SuppressWarnings("unchecked")
	private String getHtmlDetails(String tag, HttpServletRequest request)
			throws Exception {
		StringBuffer buffer = new StringBuffer();
		String msgID = request.getParameter("msgID");
		// msgID=123
		String nl = "\r\n";
		String br = "<br>";
		buffer.append("<html>").append(nl);
		buffer.append("<body>").append(nl);
		buffer.append("MSG_ID = " + msgID + ";").append(br).append(nl);
		Enviroment env = Enviroment.getInstance();
		Document doc = env.getDocument();
		Prescription pr = new Prescription();
		pr.setTag(tag);
		ObjectSearch search = new ObjectSearch(doc,
				"com.alianzamedica.connection.ConnectionImpl");
		Iterator iterator = search.searchObjects(pr).iterator();
		Prescription prescription = null;
		if (iterator.hasNext()) {
			prescription = (Prescription) iterator.next();
		}
		if (prescription != null) {
			PrescriptionDetail pdet = new PrescriptionDetail();
			pdet.setPrescriptionId(prescription.getId());
			Iterator<PrescriptionDetail> iterator0 = search.searchObjects(pdet)
					.iterator();
			int i = 1;
			while (iterator0.hasNext()) {
				PrescriptionDetail detail = iterator0.next();
				Drug drug = detail.getDrug();
				float quantity = detail.getQuantity();
				Integer barCode = drug.getBarcode();
				String ref = "REF_" + i + " = " + barCode + ";";
				Float result = quantity - detail.getQuantitySold();
				Integer iResult = result.intValue();
				// if( iResult != 0 ){
				String nb = "NB_" + i + " = " + iResult + ";";
				buffer.append(ref + nb).append(br).append(nl);
				i++;
				// }
			}

		}
		buffer.append("</body>").append(nl);
		buffer.append("</html>");
		return buffer.toString();
	}

	private void getPrescriptionDetails(HttpServletRequest request,
			PrintWriter out) throws Exception {
		String tag = request.getParameter("tagID");
		if (tag == null) {
			StringBuffer buffer = new StringBuffer();
			String nl = "\r\n";
			buffer.append("<html>").append(nl);
			buffer.append("<body>").append(nl);
			buffer.append("no se ha especificado el parametro tag");
			buffer.append("</html>").append(nl);
			buffer.append("</body>");
			out.print(buffer.toString());
		} else {
			tag = tag.replaceAll("0x", "");
			TagModel tModel = new TagModel();
			if (tModel.exists(tag)) {
				if (tModel.isUsed(tag)) {
					String respuesta = this.getHtmlDetails(tag, request);
					out.print(respuesta);
				} else {
					StringBuffer buffer = new StringBuffer();
					String nl = "\r\n";
					buffer.append("<html>").append(nl);
					buffer.append("<body>").append(nl);
					buffer.append("el tag no esta asignado a una receta");
					buffer.append("</html>").append(nl);
					buffer.append("</body>");
					out.print(buffer.toString());
				}
			} else {
				StringBuffer buffer = new StringBuffer();
				String nl = "\r\n";
				buffer.append("<html>").append(nl);
				buffer.append("<body>").append(nl);
				buffer.append("no existe el tag");
				buffer.append("</html>").append(nl);
				buffer.append("</body>");
				out.print(buffer.toString());
			}

		}

	}

	@SuppressWarnings("unchecked")
	private void getUpdater(HttpServletRequest request, PrintWriter out)
			throws Exception {
		String tag = request.getParameter("tagID");
		tag = tag.replaceAll("0x", "");
		Prescription prescription = this.getPrescriptionFromTag(tag);
		Enumeration enumeration = request.getParameterNames();
		PrescriptionSellingModel sellModel = new PrescriptionSellingModel();
		ArrayList<PrescriptionDetail> details = new ArrayList<PrescriptionDetail>();
		while (enumeration.hasMoreElements()) {
			String parameter = (String) enumeration.nextElement();
			if (parameter.startsWith("R")) {
				String num = parameter.replaceAll("R", "");
				Integer number = Integer.valueOf(num);
				String barCode = request.getParameter(parameter);
				String remain = request.getParameter("S" + number);
				@SuppressWarnings("unused")
				Float remainQuantity = Float.valueOf(remain);
				String n = request.getParameter("N" + number);
				Float soldQuantity = Float.parseFloat(n);
				PrescriptionDetail detail = sellModel.getDetailFromBarCode(
						prescription, barCode);
				float currentSold = detail.getQuantitySold();
				detail.setQuantitySold(soldQuantity + currentSold);

				@SuppressWarnings("unused")
				String p = request.getParameter("P" + number);
				details.add(detail);
			}
		}
		sellModel.updateSellDetails(details);
	}

	private String showAck(String msgID) {
		String nl = "\r\n";
		StringBuffer ack = new StringBuffer();
		ack.append("<html>").append(nl);
		ack.append("<body>").append(nl);
		ack.append("MSGID = " + msgID + ";</br>").append(nl);
		ack.append("UPDATE = ACK;</br>").append(nl);
		ack.append("</body>").append(nl);
		ack.append("</html>").append(nl);
		return ack.toString();
	}

	@SuppressWarnings("unchecked")
	private Prescription getPrescriptionFromTag(String tag) throws Exception {
		Enviroment env = Enviroment.getInstance();
		Document doc = env.getDocument();
		ObjectSearch search = new ObjectSearch(doc,
				"com.alianzamedica.connection.ConnectionImpl");
		Prescription p = new Prescription();
		p.setTag(tag);
		Iterator<Prescription> iterator = search.searchObjects(p).iterator();
		Prescription prescription = null;
		while (iterator.hasNext()) {
			prescription = (Prescription) iterator.next();
		}
		return prescription;
	}

	private String showConfig(String imei) throws Exception {
		StringBuffer buffer = new StringBuffer();
		String nl = "\r\n";
		String br = "<br>";
		buffer.append("<html>").append(nl);
		buffer.append("<body>").append(nl);
		int msgID = this.getNextMSGID(imei);
		buffer.append("MSGID = " + msgID + ";</br>").append(nl);
		String sql = "SELECT cfg.Num_ligne_prix as Num_ligne_prix,"
				+ " cfg.Num_produit AS DRUG_ID  FROM cfg_ligne_prix as cfg, "
				+ " platine as p WHERE p.Num_serie_modem = ?  "
				+ " AND cfg.Num_platine = p.Num_platine AND    "
				+ " cfg.Num_produit <> 0 ORDER BY Num_ligne_prix ASC";
		ConnectionImpl impl = new ConnectionImpl();
		PreparedStatement psmt = null;
		ResultSet rs = null;
		try {
			impl.open();
			Connection con = impl.getConnection();
			psmt = con.prepareStatement(sql);
			psmt.setString(1, imei);
			rs = psmt.executeQuery();
			StringBuffer fragment = new StringBuffer();
			int lines = 0;
			while (rs.next()) {
				int numLine = rs.getInt("Num_ligne_prix");
				int drugId = rs.getInt("DRUG_ID");
				String lineConfig = "LINE_" + numLine + " = " + drugId + ";"
						+ br + nl;
				fragment.append(lineConfig);
				lines++;
			}
			buffer.append("NB = " + lines + ";</br>").append(nl);
			buffer.append(fragment.toString());
			buffer.append("</body>").append(nl);
			buffer.append("</html>").append(nl);
		} finally {
			try {
				rs.close();
			} catch (Exception e) {
			}
			try {
				psmt.close();
			} catch (Exception e) {
			}
			try {
				impl.close();
			} catch (Exception e2) {
			}
		}
		return buffer.toString();

	}

	/**
	 * calcula el proximo imei del mensaje.
	 * 
	 * @param imei
	 *            imei del modem.
	 * @return el proximo numero del imei.
	 */
	public int getNextMSGID(String imei) {
		String sql = "select ifnull(max(numero_message),0)+1 as nextmsg from platine where num_serie_platine = ? ";
		int msgId = 1;
		ConnectionImpl impl = new ConnectionImpl();
		PreparedStatement psmt = null;
		ResultSet rs = null;
		try {
			impl.open();
			Connection con = impl.getConnection();
			psmt = con.prepareStatement(sql);
			psmt.setString(1, imei);
			rs = psmt.executeQuery();
			while (rs.next()) {
				msgId = rs.getInt(1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeGraceFully(rs);
			closeGraceFully(psmt);
			try {
				impl.close();
			} catch (Exception e) {
			}
		}
		return msgId;
	}

	private void closeGraceFully(ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (Exception e) {
			}
		}
	}

	private void closeGraceFully(PreparedStatement psmt) {
		if (psmt != null) {
			try {
				psmt.close();
			} catch (Exception e) {
			}
		}
	}

	@SuppressWarnings("unused")
	private void closeGraceFully(Statement stmt) {
		if (stmt != null) {
			try {
				stmt.close();
			} catch (Exception e) {
			}
		}
	}

}
